<template>
  <view-box ref="viewBox" class="container" body-padding-bottom="55px">
    <div id="address-container" @click="jumpAddress">
      <div class="address" v-if="checkedAddress">
        <div class="address-location">
          <span class="iconfont icon-scdizhi"></span>
        </div>
        <div class="address-main-info">
          <div class="address-receiver">
              <span class="address-receiver-name">{{checkedAddress.consignee}}</span>
              <span class="address-receiver-mobile">{{checkedAddress.phone}}</span>
          </div>
          <div class="address-detail">
              {{checkedAddress.province}}&nbsp;{{checkedAddress.city}}&nbsp;{{checkedAddress.district}}&nbsp;{{checkedAddress.address}}
          </div>
        </div>
        <div class="address-right-arrow">
          <span class="iconfont icon-fon10"></span>
        </div>
      </div>
      <div v-else class="add-address">
        <div class="add-icon">
          <span class="iconfont icon-tianjia"></span>
        </div>
        <div class="add-tip">手动添加收货地址</div>
        <div class="arrow-icon">
          <span class="iconfont icon-fon10"></span>
        </div>
      </div>
    </div>
    <div class="p-container">
      <div class="row-box" v-for="(item, index) in cartChecked" :key="index">
        <div class="p-img">
          <img :src="item.goods.thumb_img" alt="">
        </div>
        <div class="p-info">
          <div>
            <div class="p-name">
              {{item.goods.name}}
            </div>
            <div class="p-spec" v-if="item.spec">
              {{item.spec.value}}
            </div>
          </div>
          <div class="p-action">
            <div>
              <span class="p-shop-price">￥{{item.price}}</span>
            </div>
            <div>
              <inline-x-number :min="1" :max="item.stock" v-model="item.quantity" width="30px"></inline-x-number>
            </div>
          </div>
        </div>
      </div>
    </div>
    <group title="支付方式" v-if="action !== 'zhuangbi_buy' && action !== 'qingbi_buy'">
       <radio :options="options" v-model="payType">
        <template slot-scope="props" slot="each-item">
          <p class="pay-type">
            <i :class="props.icon" class="pay-icon"></i> {{ props.label }}
            <span v-if="props.index === 1" style="font-size: 13px; color: #999; margin-left: 5px;">可用余额{{userInfo.balance}}元</span>
          </p>
        </template>
      </radio>
    </group>
    <group title="优惠方式" v-if="action !== 'zhuangbi_buy' && action !== 'qingbi_buy'">
      <!-- <cell title="优惠券" is-link @click.native="jumpCoupon">{{chocieCouponTips}}</cell> -->
      <x-switch :disabled="availableIntegralNumber <= 0" :title="'可使用'+availableIntegralNumber+'积分抵扣'+availableIntegralPrice+'元'" v-model="useIntegral"></x-switch>
    </group>
    <group class="clear-margin" v-if="action !== 'zhuangbi_buy' && action !== 'qingbi_buy'">
      <cell-form-preview :list="list"></cell-form-preview>
    </group>
    <div slot="bottom" class="action-bar" v-if="action !== 'zhuangbi_buy' && action !== 'qingbi_buy'">
      <div class="p-total-price">
        实付款：<strong>￥{{cartCheckedPayTotal}}</strong>
      </div>
      <div class="p-btn">
        <x-button @click.native="generateOrder" type="warn" :disabled="loading" :show-loading="loading">立即支付</x-button>
      </div>
    </div>
    <div slot="bottom" class="action-bar" v-else>
      <div class="p-btn" style="width: 1000%;">
        <x-button @click.native="generateOrder" type="warn" :disabled="loading" :show-loading="loading">立即兑换</x-button>
      </div>
    </div>
  </view-box>
</template>
<script>
  import { ViewBox, InlineXNumber, Group, Cell, XSwitch, CellFormPreview, XButton, Radio } from 'vux'
  import { mapGetters } from 'vuex'
  import { SET_REFER_PAGE } from '@/store/mutation-types'
  export default {
    data () {
      return {
        value: 2,
        useIntegral: false,
        payType: 'WXPAY',
        loading: false
      }
    },
    components: {
      ViewBox,
      InlineXNumber,
      Group,
      Cell,
      XSwitch,
      CellFormPreview,
      XButton,
      Radio
    },
    computed: {
      ...mapGetters([
        'cartChecked',
        'cartCheckedCoupon',
        'cartCheckedTotalPrice',
        'cartCheckedFullCut',
        'availableIntegralPrice',
        'availableIntegralNumber',
        'cartCheckedShippingFee',
        'cartCheckedCouponPrice',
        'checkedAddress'
      ]),
      action () {
        return this.$store.state.cart.action
      },
      options () {
        return [{
          icon: 'iconfont icon-weixinzhifu',
          key: 'WXPAY',
          value: '微信支付'
        }, {
          icon: 'iconfont icon-zhanghuyue',
          key: 'BALANCE',
          value: '余额支付'
        }]
      },
      userInfo () {
        return this.$store.getters.userInfo
      },
      cartCheckedPayTotal () {
        return this.$store.getters.cartCheckedPayTotal(this.useIntegral)
      },
      chocieCouponTips () {
        if (this.cartCheckedCoupon !== null) {
          return this.cartCheckedCoupon.money + '元优惠券'
        } else {
          return '请选择'
        }
      },
      list () {
        return [{
          label: '商品总金额',
          value: '￥' + this.cartCheckedTotalPrice
        }, {
          label: '会员折扣',
          value: this.userInfo.level.discount_desc
        }, {
          label: '满减优惠',
          value: this.cartCheckedFullCut
        }, {
          label: '优惠券',
          value: this.cartCheckedCouponPrice
        }, {
          label: '积分抵扣',
          value: this.useIntegral ? this.availableIntegralPrice : 0
        }, {
          label: '运费',
          value: this.cartCheckedShippingFee
        }]
      }
    },
    methods: {
      jumpAddress () {
        this.$store.commit(SET_REFER_PAGE, '/checkout')
        this.$router.replace('/addresses')
      },
      jumpCoupon () {
        this.$router.push('/coupons?refer=/checkout')
      },
      generateOrder () {
        // check product data
        if (this.cartChecked.length === 0) {
          this.$vux.toast.show('未选择商品')
          return false
        }
        // check address
        if (!this.checkedAddress) {
          this.$vux.toast.show('请选择收货地址')
          return false
        }
        // balance pay
        if (this.payType === 'BALANCE' && this.userInfo.balance < this.cartCheckedPayTotal) {
          let _this = this
          this.$vux.confirm.show({
            title: '余额不足',
            confirmText: '点击查看',
            cancelText: '其他方式',
            content: '请选择其他支付方式支付，或者立即充值',
            onCancel () {
              _this.payType = 'WXPAY'
            },
            onConfirm () {
              _this.$router.push('/balances')
            }
          })
          return false
        }
        let data = {
          cart: this.cartChecked,
          address_id: this.checkedAddress.id,
          integral: this.useIntegral ? this.availableIntegralNumber : 0,
          action: this.$store.state.cart.action,
          team_found_id: this.$store.state.cart.teamFoundId,
          user_coupon_id: this.$store.state.cart.checkedCoupon ? this.$store.state.cart.checkedCoupon.id : 0,
          pay_code: this.payType
        }
        this.loading = true
        this.$http.post('/orders', data).then((response) => {
          // 订单金额为零时，不需要支付
          if (response.data.pay_status === 1) {
            this.$router.replace('/orders?type=0')
          } else if (response.data.pay_code === 'BALANCE') {
            this._balancePay(response.data.id)
          } else {
            // 微信支付
            this._pay(response.data.id)
          }
        }).catch((error) => {
          this.loading = false
          console.log(error)
        })
      },
      _balancePay (id) {
        this.$http.get('/pay/balance-' + id).then((response) => {
          this.$store.dispatch('getUserInfo')
          this.$router.replace('/orders?type=0')
        }).catch((error) => {
          console.log(error)
          this.$router.replace('/orders?type=0')
        })
      },
      _pay (id) {
        let json = {}
        let callpay = () => {
          if (typeof WeixinJSBridge === 'undefined') {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false)
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', onBridgeReady)
              document.attachEvent('onWeixinJSBridgeReady', onBridgeReady)
            }
          } else {
            onBridgeReady()
          }
        }
        let onBridgeReady = () => {
          WeixinJSBridge.invoke('getBrandWCPayRequest', json, (res) => {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              this.$router.replace('/orders?type=0')
            } else {
              this.$router.replace('/orders?type=0')
            }
          })
        }
        this.$http.get('/pay/wxpay-' + id).then((response) => {
          json = response.data
          callpay()
        }).catch((error) => {
          console.log(error)
        })
      }
    },
    mounted () {
    }
  }
</script>
<style scoped lang="less">
  .container {
    background: #f2f2f2;
  }
  .address, .add-address {
    display: flex;
    align-items: center;
    width: 100%;
    background-color: #fff;
    color: #151516;
    font-size: 13px;
    overflow-x: hidden;
    justify-content: flex-start;
    position: relative;
  }
  .address {
    min-height: 74px;
  }
  .add-address {
    height: 47px;
    line-height: 47px;
    font-size: 14px;
  }
  .address .address-location, .add-address .add-icon{
    width: 44px;
    height: 100%;
    text-align: center;
    color: #58595b;
  }
  .add-icon .iconfont {
    color: @tabbar-text-active-color;
    font-size: 25px;
  }
  .address .address-main-info, .add-address .add-tip {
    flex: 1;
  }
  .address .address-main-info .address-receiver {
    margin-bottom: 3px;
  }
  .address .address-main-info .address-receiver .address-receiver-name{
    font-size: 16px;
    font-weight: 700;
    margin-right: 11px;
  }
  .address .address-main-info .address-receiver .address-receiver-mobile{
    font-size: 14px;
  }
  .address .address-main-info .address-detail {
    word-break: break-all;
    width: 100%;
    line-height: 1.4;
  }
  .address .address-right-arrow, .add-address .arrow-icon {
    width: 31px;
    color: #58595b;
    text-align: center;
  }
  .address:before {
    content: "";
    position: absolute;
    display: inline-block;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background-position: 0 0;
    background-size: 100% 2px;
    background-image: url()
  }
  .p-container {
    margin-top: 6px;
  }
  .row-box {
    display: flex;
    padding-right: 10px;
    justify-content:space-between;
    height: 90px;
    padding-bottom: 10px;
    padding-top: 10px;
    background: #fff;
    margin-bottom: 1px;
  }
  .p-img {
    flex-shrink: 0;
    width: 90px;
    padding-right: 10px;
    padding-left: 10px;
  }
  .p-img img {
    width: 90px;
    height: 90px;
  }
  .row-box .p-info {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .row-box .p-info .p-name {
    font-size: 14px;
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    padding-bottom: 5px;
    color: #151516;
  }
  .row-box .p-info .p-action {
    color: @tabbar-text-active-color;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
  }
  .row-box .p-info .p-action .weui-btn {
    margin-right: 0;
  }
  .row-box  .p-info .p-action .p-shop-price {
    font-size: 16px;
    font-weight: 500;
    line-height: 16px;
    height: 16px;
  }
  .row-box  .p-info .p-action .p-market-price {
    font-size: 12px;
    height: 12px;
    line-height: 12px;
    color: #9c9c9c;
  }
  .p-spec {
    font-size: 12px;
    color: #9c9c9c;
  }
  .clear-margin {
    margin-top: -15px;
  }
  .action-bar {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    position: fixed;
    z-index: 500;
    bottom: 0px;
    width: 100%;
    height: 42px;
    line-height: 42px;
  }
  .p-total-price {
    flex: 1;
    text-align: right;
    color: @tabbar-text-active-color;
    padding-right: 10px;
  }
  .p-btn {
    width: 150px;
    text-align: center;
    color: #fff;
    .weui-btn {
      border-radius: 0;
      border: none;
      &:after {
        border-radius: 0;
      border: none;
      }
    }
  }
  .pay-type {
    line-height: 25px;
  }
  .pay-icon {
    color: #04BE02;
    font-size: 25px;
    margin-right: 10px;
  }
</style>